import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Scanner;
import java.lang.reflect.*;

public class JShell {

	private FileSystem mocksystem;
	private Hashtable<String, String> commandlist = new Hashtable<String, String>();

	public JShell() {
		mocksystem = FileSystem.getInstance();
		generateCommands();
	}

	private void generateCommands() {
		commandlist.put("cd", "CD");
		commandlist.put("mkdir", "MKDIR");
		commandlist.put("ls", "LS");
		commandlist.put("pwd", "PWD");
		commandlist.put("mv", "MV");
		commandlist.put("cp", "CP");
		commandlist.put("cat", "CAT");
		commandlist.put("get", "GET");
		commandlist.put("echo", "ECHO");
		commandlist.put("ln", "LN");
		commandlist.put("man", "MAN");
	}

	public ArrayList<String> parseInput(String line) {
		char[] charlist = line.trim().toCharArray();
		String word = "";
		ArrayList<String> arraylistline = new ArrayList<String>();
		boolean inquotes = false;

		for (char i : charlist) {
			if (String.valueOf(i).equals("\"")) {
				inquotes = !inquotes;
				continue;
			}
			if (!inquotes && String.valueOf(i).equals(" ")) {
				if (!word.equals("")) {
					arraylistline.add(word);
					word = "";
				}
				continue;
			}
			word += i;
		}
		if (word != "")
			arraylistline.add(word);
		return arraylistline;
	}

	public void startShell() {
		Scanner reader = new Scanner(System.in);
		boolean done = false;

		while (!done) {
			System.out.print(mocksystem.getItemPath(mocksystem.getCurrentdir())
					+ "# ");

			String userinput = reader.nextLine();
			ArrayList<String> inputarray = parseInput(userinput);

			if (inputarray.get(0).equals("exit")) {
				done = true;
				break;
			}
			this.selectCommand(inputarray);
		}
		reader.close();
	}

	private void selectCommand(ArrayList<String> inputarray) {
		try {
			String classname = commandlist.get(inputarray.get(0));
			Class cls = Class.forName(classname);
			Class[] parttypes = { ArrayList.class };
			Constructor ct = cls.getConstructor(parttypes);
			Object[] arglist = new Object[1];
			arglist[0] = inputarray;
			Object retobj = ct.newInstance(arglist);
			Command com = (Command) retobj;

			if (inputarray.contains(">") || inputarray.contains(">>"))
				com.toFile();
			else
				com.execute();
		} catch (Throwable e) {
			System.out.println("Sorry, command does not exist.");
		}
	}

	public static void main(String[] args) {
		JShell shell = new JShell();
		shell.startShell();
	}
}
